package ltd.newbee.mall.api.mall;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import ltd.newbee.mall.api.mall.param.SaveCartItemParam;
import ltd.newbee.mall.api.mall.param.UpdateCartItemParam;
import ltd.newbee.mall.api.mall.vo.NewBeeMallShoppingCartItemVO;
import ltd.newbee.mall.common.NewBeeMallException;
import ltd.newbee.mall.common.ServiceResultEnum;
import ltd.newbee.mall.config.annotation.TokenToMallUser;
import ltd.newbee.mall.entity.MallUser;
import ltd.newbee.mall.entity.NewBeeMallShoppingCartItem;
import ltd.newbee.mall.entity.PageQuery;
import ltd.newbee.mall.entity.PageResult;
import ltd.newbee.mall.service.NewBeeMallShoppingCartService;
import ltd.newbee.mall.util.Result;
import ltd.newbee.mall.util.ResultGenerator;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Tag(name = "5.新蜂商城购物车相关接口")
@RequestMapping("/api/v1")
public class NewBeeMallShoppingCartAPI {
    @Resource
    private NewBeeMallShoppingCartService newBeeMallShoppingCartService;

    @GetMapping("/shop-cart/page")
    @Operation(summary = "购物车列表(每页默认20条)", description = "传参为页码")
    public Result<PageResult<List<NewBeeMallShoppingCartItemVO>>> cartItemPageList(
            @RequestParam(required = false) @Parameter(name = "pageIndex", description = "页码") Integer pageIndex,
            @RequestParam(required = false, defaultValue = "20") @Parameter(name = "pageSize", description = "大小") Integer pageSize,
            @Parameter(hidden = true) @TokenToMallUser MallUser loginMallUser
    ) {
        Map params = new HashMap(4);
        if (pageIndex == null || pageIndex < 1) {
            pageIndex = 1;
        }
        params.put("userId", loginMallUser.getUserId());
        params.put("pageSize", pageSize);
        params.put("pageIndex", pageIndex);
        PageQuery pageQuery = new PageQuery(params);
        return ResultGenerator.genSuccessResult(newBeeMallShoppingCartService.getMyShoppingCartItems(pageQuery));
    }

    @GetMapping("/shop-cart")
    @Operation(summary = "购物车列表(网页移动端不分页)", description = "")
    public Result<List<NewBeeMallShoppingCartItemVO>> cartItemList(
            @Parameter(hidden = true) @TokenToMallUser MallUser loginMallUser
    ) {
        return ResultGenerator.genSuccessResult(newBeeMallShoppingCartService.getMyShoppingCartItems(loginMallUser.getUserId()));
    }

    @PostMapping("/shop-cart")
    @Operation(summary = "添加商品到购物车接口", description = "参数为商品id、数量")
    public Result<NewBeeMallShoppingCartItemVO> saveNewBeeMallShoppingCartItem(
            @RequestBody SaveCartItemParam saveCartItemParam,
            @Parameter(hidden = true) @TokenToMallUser MallUser loginMallUser
    ) {
        String saveResult = newBeeMallShoppingCartService.saveNewBeeMallCartItem(saveCartItemParam, loginMallUser.getUserId());
        //添加成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(saveResult)) {
            return ResultGenerator.genSuccessResult();
        }
        //添加失败
        return ResultGenerator.genFailResult(saveResult);
    }

    @PutMapping("/shop-cart")
    @Operation(summary = "修改购物项数据", description = "传参为购物项id、数量")
    public Result updateNewBeeMallShoppingCartItem(
            @RequestBody UpdateCartItemParam updateCartItemParam,
            @Parameter(hidden = true) @TokenToMallUser MallUser loginMallUser
    ) {
        String updateResult = newBeeMallShoppingCartService.updateNewBeeMallCartItem(updateCartItemParam, loginMallUser.getUserId());
        //修改成功
        if (ServiceResultEnum.SUCCESS.getResult().equals(updateResult)) {
            return ResultGenerator.genSuccessResult();
        }
        //修改失败
        return ResultGenerator.genFailResult(updateResult);
    }

    @DeleteMapping("/shop-cart/{newBeeMallShoppingCartItemId}")
    @Operation(summary = "删除购物项", description = "传参为购物项id")
    public Result updateNewBeeMallShoppingCartItem(
            @PathVariable("newBeeMallShoppingCartItemId") Long newBeeMallShoppingCartItemId,
            @Parameter(hidden = true) @TokenToMallUser MallUser loginMallUser
    ) {
        NewBeeMallShoppingCartItem newBeeMallCartItemById = newBeeMallShoppingCartService.getNewBeeMallCartItemById(newBeeMallShoppingCartItemId);
        if (!loginMallUser.getUserId().equals(newBeeMallCartItemById.getUserId())) {
            return ResultGenerator.genFailResult(ServiceResultEnum.REQUEST_FORBIDEN_ERROR.getResult());
        }
        Boolean deleteResult = newBeeMallShoppingCartService.deleteById(newBeeMallShoppingCartItemId, loginMallUser.getUserId());
        //删除成功
        if (deleteResult) {
            return ResultGenerator.genSuccessResult();
        }
        //删除失败
        return ResultGenerator.genFailResult(ServiceResultEnum.OPERATE_ERROR.getResult());
    }

    @GetMapping("/shop-cart/settle")
    @Operation(summary = "根据购物项id数组查询购物项明细", description = "确认订单页面使用")
    public Result<List<NewBeeMallShoppingCartItemVO>> toSettle(
            Long[] cartItemIds,
            @Parameter(hidden = true) @TokenToMallUser MallUser loginMallUser
    ) {
        if (cartItemIds.length < 1) {
            NewBeeMallException.fail("参数异常");
        }
        int priceTotal = 0;
        List<NewBeeMallShoppingCartItemVO> itemsForSettle = newBeeMallShoppingCartService.getCartItemsForSettle(Arrays.asList(cartItemIds), loginMallUser.getUserId());
        if (CollectionUtils.isEmpty(itemsForSettle)) {
            //无数据则抛出异常
            NewBeeMallException.fail("参数异常");
        } else {
            //总价
            for (NewBeeMallShoppingCartItemVO newBeeMallShoppingCartItemVO : itemsForSettle) {
                priceTotal += newBeeMallShoppingCartItemVO.getGoodsCount() * newBeeMallShoppingCartItemVO.getSellingPrice();
            }
            if (priceTotal < 1) {
                NewBeeMallException.fail("价格异常");
            }
        }
        return ResultGenerator.genSuccessResult(itemsForSettle);
    }
}
